﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NetPE.Disasm.CIL;
using NetPE.Core.Metadata.Methods;

namespace NetPE
{
    public partial class CilDisassembly : Form
    {
        public CilDisassembly()
        {
            InitializeComponent();
        }

        public void Disassemble(ManagedMethodBody bdy)
        {
            InstructionCollection insts = Disassembler.Disassemble(bdy.Codes);
            foreach (Instruction i in insts)
            {
                ListViewItem item = new ListViewItem(i.GetOffsetString());
                item.SubItems.Add(new ListViewItem.ListViewSubItem(item, i.OpCode.ToString()) { ForeColor = Color.Blue });
                if (i.Operand != null)
                    item.SubItems.Add(new ListViewItem.ListViewSubItem(item, i.Operand.ToString()) { ForeColor = Color.Green });
                listView1.Items.Add(item);
            }

            foreach (DataSection sect in bdy.DataSections)
            {
                foreach (ExceptionClause i in sect)
                {
                    string text = ".try L_";
                    text += i.TryOffset.ToString("x4").ToUpper();
                    text += " to L_";
                    text += (i.TryOffset + i.TryLength).ToString("x4").ToUpper();

                    if (i.Flags == ExceptionClauseFlags.Exception)
                    {
                        text += " catch [0x" + i.ClassToken.Token.Value.ToString("x8").ToUpper() + "] handler L_";
                    }
                    else if (i.Flags == ExceptionClauseFlags.Filter)
                    {
                        text += " filter L_" + i.FilterOffset.ToString("x8").ToUpper() + " handler L_";
                    }
                    else if (i.Flags == ExceptionClauseFlags.Finally)
                    {
                        text += " finally handler L_";
                    }
                    else if (i.Flags == ExceptionClauseFlags.Fault)
                    {
                        text += " fault handler L_";
                    }

                    text += i.HandlerOffset.ToString("x4").ToUpper();
                    text += " to L_";
                    text += (i.HandlerOffset + i.HandlerLength).ToString("x4").ToUpper();
                    listView2.Items.Add(new ListViewItem(text));
                }
            }
        }
    }
}
